package com.voicechat.firstmet.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tencent.TIMFriendGenderType;
import com.tencent.TIMFriendshipManager;
import com.tencent.TIMUserProfile;
import com.tencent.TIMValueCallBack;
import com.voicechat.firstmet.App;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.base.BaseAdapter;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.imcontrol.Conversation;
import com.voicechat.firstmet.imcontrol.NomalConversation;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.utils.GlideLoadUtils;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.Utils;
import com.voicechat.firstmet.view.CircleImageView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.adapter
 * @ClassName: IMessageConversationAdapter
 * @Description: 会话列表adapter
 * @Author: ljp
 * @CreateDate: 2018/11/12 10:01
 * @Version: 1.0
 */
public class IMessageConversationAdapter extends BaseAdapter<Conversation> {
    private OnItemClickListener itemClickListener;
    private ItemClick itemClick;
    private String TAG = "IMessageConversationAdapter";
    private List<String> users;

    public void setItemClick(ItemClick itemClick) {
        this.itemClick = itemClick;
    }

    public void setItemClickListener(OnItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    /**
     * @param context activity_imessage
     * @param tlist   集合
     * @param mLayout 主布局
     */
    public IMessageConversationAdapter(Context context, List<Conversation> tlist, int mLayout) {
        super(context, tlist, mLayout);
        //待获取用户资料的用户列表
        users = new ArrayList<String>();
    }

    @Override
    protected RecyclerView.ViewHolder getHeaderViewHolder(View view) {
        return new HeadViewHolder(view);
    }

    @Override
    protected RecyclerView.ViewHolder getItemViewHolder(View view) {
        return new ItemViewHolder(view);
    }

    @Override
    protected RecyclerView.ViewHolder getFooterViewHolder(View view) {
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        if (viewHolder instanceof HeadViewHolder) {
            HeadViewHolder headViewHolder = (HeadViewHolder) viewHolder;
            headViewHolder.relaOfficialMsg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //官方通知
                    itemClick.setItemClick("Official");
                }
            });
            headViewHolder.relaSteamMsg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //系统消息
                    itemClick.setItemClick("Steam");
                }
            });
            headViewHolder.relaAddFriendMsg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //headViewHolder.imageReadFriend.setVisibility(View.GONE);
                    //系统消息
                    itemClick.setItemClick("friends");
                }
            });
            httpMsgFriends(headViewHolder.imageReadFriend);
            httpMsgSystem(headViewHolder.imageRead);
        } else if (viewHolder instanceof ItemViewHolder) {
            if (position == 0) {
                return;
            }
            position = position - 1;
            ItemViewHolder itemViewHolder = (ItemViewHolder) viewHolder;
            final NomalConversation data = (NomalConversation) tlist.get(position);
          /*  if( !data.getIdentify().equals(itemViewHolder.avatar.getTag(R.id.avatar))){
                itemViewHolder.avatar.setTag(R.id.avatar,data.getIdentify());
                getUserMessageOther(data.getIdentify(),itemViewHolder.name,itemViewHolder.avatar,itemViewHolder.imageVip,itemViewHolder.linearSexAge
                ,itemViewHolder.imageSex,itemViewHolder.tvAge,itemViewHolder.imageIsanchor);
            }*/
            //   if (!TextUtils.isEmpty(data.getAvatar()) && !data.getAvatar().equals(itemViewHolder.avatar.getTag(R.id.avatar))) {
            //   itemViewHolder.avatar.setTag(R.id.avatar, data.getAvatar());
            if (!TextUtils.isEmpty(data.getIdentify() )) {
                if (!TextUtils.isEmpty(data.getName())) {
                    //  Log.i(TAG, "onBindViewHolder: ---data------"+data.toString());
                    itemViewHolder.name.setText(data.getName());
                    if (!TextUtils.isEmpty(data.getAvatar())) {
                        if (!data.getIdentify().equals(itemViewHolder.avatar.getTag(R.id.avatar))) {
                            // 加载图片
                            itemViewHolder.avatar.setTag(R.id.avatar, data.getIdentify());
                            GlideLoadUtils.getInstance().glideLoad(context, OssConfig.OSS_HTTP + data.getAvatar(),
                                    itemViewHolder.avatar);
                        }
                    }
                    if (!TextUtils.isEmpty(data.getIsVip())) {
                        if (data.getIsVip().equals("0")) {// 会员等级 0非会员 1月会员 2年会员
                            itemViewHolder.imageVip.setVisibility(View.GONE);
                        } else if (data.getIsVip().equals("1")) {
                            itemViewHolder.imageVip.setVisibility(View.VISIBLE);
                            itemViewHolder.imageVip.setImageResource(R.mipmap.vip_month);
                        } else if (data.getIsVip().equals("2")) {
                            itemViewHolder.imageVip.setVisibility(View.VISIBLE);
                            itemViewHolder.imageVip.setImageResource(R.mipmap.vip_year);
                        }
                    }
                    if (data.getSex() == TIMFriendGenderType.Male) {//性别  1男2女
                        itemViewHolder.linearSexAge.setBackgroundResource(R.mipmap.sex_blue);
                        itemViewHolder.imageSex.setImageResource(R.mipmap.boy);
                    } else {
                        itemViewHolder.linearSexAge.setBackgroundResource(R.mipmap.sex_red);
                        itemViewHolder.imageSex.setImageResource(R.mipmap.girl);
                    }
                    if (!TextUtils.isEmpty(data.getBirthday())) {
                        itemViewHolder.tvAge.setText(Utils.getAge(data.getBirthday()));
                    }
                    if (!TextUtils.isEmpty(data.getIsAnchor()) && data.getIsAnchor().equals("2")) {//判断是否是主播
                        itemViewHolder.imageIsanchor.setVisibility(View.VISIBLE);
                       /* GlideLoadUtils.getInstance().glideLoad(context, OssConfig.OSS_HTTP + object.getExclusiveUrl(),
                                imageIsAnchor);*/
                    } else {
                        itemViewHolder.imageIsanchor.setVisibility(View.GONE);
                    }
                } else {
                    if (!data.getIdentify().equals(itemViewHolder.avatar.getTag(R.id.avatar))) {
                        itemViewHolder.avatar.setTag(R.id.avatar, data.getIdentify());
                        getUserMessageOther(data.getIdentify(), itemViewHolder.name, itemViewHolder.avatar, itemViewHolder.imageVip, itemViewHolder.linearSexAge
                                , itemViewHolder.imageSex, itemViewHolder.tvAge, itemViewHolder.imageIsanchor);
                    }
                    //notifyDataSetChanged();
                    //   getUserMessageOther(data.getIdentify(), itemViewHolder.name, itemViewHolder.avatar, itemViewHolder.imageVip
                    //           , itemViewHolder.linearSexAge, itemViewHolder.imageSex, itemViewHolder.tvAge, itemViewHolder.imageIsanchor);
                }
            }
          //  }
            itemViewHolder.lastMessage.setText(data.getLastMessageSummary());
            String format = "yyyy" + App.getContext().getResources().getString(R.string.time_year) + "MM" + App.getContext().getResources().getString(R.string.time_month) + "dd" + App.getContext().getResources().getString(R.string.time_day); /*+ " HH:mm"*/
            itemViewHolder.messageTime.setText(Utils.getChatTimeStr(data.getLastMessageTime(),format));
            long unRead = data.getUnreadNum();
            if (unRead <= 0) {
                itemViewHolder.unreadNum.setVisibility(View.INVISIBLE);
            } else {
                itemViewHolder.unreadNum.setVisibility(View.VISIBLE);
                String unReadStr = String.valueOf(unRead);
                if (unRead < 10) {
                    itemViewHolder.unreadNum.setBackgroundResource(R.mipmap.point1);
                } else {
                    itemViewHolder.unreadNum.setBackgroundResource(R.mipmap.point2);
                    if (unRead > 99) {
                        unReadStr = context.getResources().getString(R.string.time_more);
                    }
                }
                itemViewHolder.unreadNum.setText(unReadStr);
            }
            int finalPosition = position;
            itemViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemClickListener.OnItemClick(finalPosition, v);
                }
            });
            int finalPosition1 = position;
            itemViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    itemClick.setLongItemClick(finalPosition1);
                    return true;
                }
            });
        }
    }
    /**
     * @return
     * @method
     * @description 获取别人资料
     * @date: 2018/11/9 11:10
     * @author: ljp
     */
    private void getUserMessageOther(String identify, TextView name, CircleImageView avatar, ImageView imageVip, LinearLayout linearSexAge, ImageView imageSex, TextView tvAge, ImageView imageIsanchor) {
        users.add(identify);
        //获取用户资料
        TIMFriendshipManager.getInstance().getUsersProfile(users, new TIMValueCallBack<List<TIMUserProfile>>() {
            @Override
            public void onError(int code, String desc) {
                Log.e(TAG, "getUsersProfile failed: " + code + " desc");
            }
            @Override
            public void onSuccess(List<TIMUserProfile> result) {
                for (TIMUserProfile res : result) {
                  //  Log.e(TAG, "identifier: " + res.getIdentifier() + " nickName: " + res.getNickName()
                   //         + " getFaceUrl: " + res.getFaceUrl() + "---getGender--" + res.getGender());
                    try {
                        if (identify.equals(res.getIdentifier())) {
                            if (!TextUtils.isEmpty(res.getNickName())) {
                                String[] strings = Utils.spitInfo(res.getFaceUrl());
                                // 头像地址 + 是否会员 + 是否主播 + 生日
                                name.setText(res.getNickName());
                                if (!TextUtils.isEmpty(strings[0])) {
                                    if (!strings[0].equals(avatar.getTag(R.id.avatar))) {
                                        // 加载图片
                                        avatar.setTag(R.id.avatar, strings[0]);
                                        GlideLoadUtils.getInstance().glideLoad(context, OssConfig.OSS_HTTP + strings[0],
                                                avatar);
                                    }
                                }
                                if (!TextUtils.isEmpty(strings[1])) {
                                    if (strings[1].equals("0")) {// 会员等级 0非会员 1月会员 2年会员
                                        imageVip.setVisibility(View.GONE);
                                    } else if (strings[1].equals("1")) {
                                        imageVip.setVisibility(View.VISIBLE);
                                        imageVip.setImageResource(R.mipmap.vip_month);
                                    } else if (strings[1].equals("2")) {
                                        imageVip.setVisibility(View.VISIBLE);
                                        imageVip.setImageResource(R.mipmap.vip_year);
                                    }
                                }
                                if (res.getGender() == TIMFriendGenderType.Male) {//性别  1男2女
                                    linearSexAge.setBackgroundResource(R.mipmap.sex_blue);
                                    imageSex.setImageResource(R.mipmap.boy);
                                } else {
                                    linearSexAge.setBackgroundResource(R.mipmap.sex_red);
                                    imageSex.setImageResource(R.mipmap.girl);
                                }
                                if (!TextUtils.isEmpty(strings[3])) {
                                    tvAge.setText(Utils.getAge(strings[3]));
                                }
                                if (!TextUtils.isEmpty(strings[2]) && strings[2].equals("2")) {//判断是否是主播
                                    imageIsanchor.setVisibility(View.VISIBLE);
                                } else {
                                    imageIsanchor.setVisibility(View.GONE);
                                }
                            }
                        }
                    } catch (RuntimeException e) {

                    }

                }
            }
        });
    }
    private void httpMsgFriends(ImageView imageView){
        MySelfInfoBean.ObjectBean mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        //好友申请
        MeInfoService.friendAccept(mySeleInfo.getId(), SPUtils.getEditoString(SPUtils.SP_TOKEN), PhoneUtils.getDeviceInfo(context), 1).subscribe(coummunityNotice -> {
            if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                imageView.setVisibility(coummunityNotice.isObject() ? View.VISIBLE : View.GONE);
            } else if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
            }
        }, throwable -> {
        });
    }

    //获取系统消息未读
    private void httpMsgSystem(ImageView imageView) {
        MySelfInfoBean.ObjectBean mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        MeInfoService.systemMessage(mySeleInfo.getId(), SPUtils.getEditoString(SPUtils.SP_TOKEN), PhoneUtils.getDeviceInfo(context), "", "1").subscribe(coummunityNotice -> {
            // Log.i(TAG, "setHttpData: ----"+coummunityNotice.getPage().getList().size());
            if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                //Log.i(TAG, "setHttpData: ---getCount---"+coummunityNotice.getPage().getCount());
                imageView.setVisibility(coummunityNotice.getPage().getCount() == 0 ? View.GONE : View.VISIBLE);
            } else if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                //.toast_MakeText(coummunityNotice.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "setHttpData: ----" + throwable.toString());
            // context.toast_MakeText(context.getResources().getString(R.string.net_error));
        });
    }

    /**
     * @method
     * @description 会话记录头布局
     * @date: 2018/11/12 10:03
     * @author: ljp
     * @return
     */
    class HeadViewHolder extends BaseViewHolder {
        @BindView(R.id.rela_steam_msg)
        RelativeLayout relaSteamMsg;
        @BindView(R.id.rela_official_msg)
        RelativeLayout relaOfficialMsg;
        @BindView(R.id.rela_add_friends_msg)
        RelativeLayout relaAddFriendMsg;
        @BindView(R.id.image_read)
        ImageView imageRead;
        @BindView(R.id.image_read_friend)
        ImageView imageReadFriend;
        public HeadViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    /**
     * @method
     * @description 会话记录
     * @date: 2018/11/12 10:02
     * @author: ljp
     * @return
     */
    class ItemViewHolder extends BaseViewHolder {
        @BindView(R.id.avatar)
        CircleImageView avatar;
        @BindView(R.id.name)
        TextView name;
        @BindView(R.id.last_message)
        TextView lastMessage;
        @BindView(R.id.message_time)
        TextView messageTime;
        @BindView(R.id.unread_num)
        TextView unreadNum;
        View itemView;
        @BindView(R.id.image_isanchor)
        ImageView imageIsanchor;
        @BindView(R.id.image_sex)
        ImageView imageSex;
        @BindView(R.id.tv_age)
        TextView tvAge;
        @BindView(R.id.linear_sex_age)
        LinearLayout linearSexAge;
        @BindView(R.id.image_vip)
        ImageView imageVip;

        public ItemViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            this.itemView = itemView;
        }
    }

    public interface ItemClick {
        void setItemClick(String type);

        void setLongItemClick(int position);
    }
}
